var self = {
	/**
	 * websocket链接
	 */
	connectSocket: function() {
		var that = this;
		let app = getApp();
		var userinfo = app.globalData.userinfo;
		if (app.globalData.wsDomain == '' || (app.globalData.chat_config.SocketTask && app.globalData.chat_config.SocketTask.readyState == 1) || !userinfo) {
			return false;
		}
		let url = app.globalData.wsDomain + '?token=' +userinfo.token;
		var SocketTask = uni.connectSocket({
			url: url,
			success: (res) => {
				console.log('wss 连接成功');
				uni.onNetworkStatusChange(function(res) {
					console.log(res.isConnected);
					console.log(res.networkType);
				});
			}
		});
		app.globalData.chat_config.SocketTask = SocketTask;
		SocketTask.onMessage((evt) => {
			var msg = JSON.parse(evt.data);
			console.log('liixixi', msg)
			if (msg.code == 0) {
				uni.showToast({title: msg.msg || '网络错误',icon: 'none'});
				return;
			}

			that.handleMsg(msg);
		});
		SocketTask.onOpen(() => {
			app.globalData.chat_config.CurrentRetryCount = 0; // 重新发送所有出错的消息

			if (app.globalData.chat_config.ErrorMsg.length > 0) {
				for (let i in app.globalData.chat_config.ErrorMsg) {
					that.wsSend(app.globalData.chat_config.ErrorMsg[i]);
				}

				app.globalData.chat_config.ErrorMsg = [];
			}

			if (app.globalData.chat_config.Timer != null) {
				clearInterval(app.globalData.chat_config.Timer);
			}

			app.globalData.chat_config.Timer = setInterval(that.wsSend, 29999); //定时发送心跳
		});
		SocketTask.onError(function(res) {
			console.log('wss:onError', res);
		});
		SocketTask.onClose(function(res) {
			console.log('关闭');

			if (app.globalData.chat_config.Timer != null) {
				clearInterval(app.globalData.chat_config.Timer);
			}

			if (app.globalData.chat_config.MaxRetryCount) {
				app.globalData.chat_config.Timer = setInterval(that.retryWebSocket, 3000); //每3秒重新连接一次
			}
		});
	},
	/**
	 * 断线重连
	 */
	retryWebSocket: function(option = {}) {
		var app = getApp();
		if (app.globalData.chat_config.CurrentRetryCount < app.globalData.chat_config.MaxRetryCount) {
			app.globalData.chat_config.CurrentRetryCount++;
			self.connectSocket();
			console.log('重连 WebSocket 第' + app.globalData.chat_config.CurrentRetryCount + '次');
		} else {
			if (app.globalData.chat_config.Timer != null) {
				clearInterval(app.globalData.chat_config.Timer);
			}
			uni.showModal({
				title: '提示',
				content: 'Websocket连接失败',
			})
			// if (app.globalData.chat_config.ReConnection) {
			// 	console.log('每隔10秒将再次尝试重连 WebSocket');
			// 	app.globalData.chat_config.Timer = setInterval(this.connectSocket, 10000); //每10秒重新连接一次
			// }
		}
	},
	/**
	 * 消息发送
	 */
	wsSend: function(message) {
		var app = getApp();
		if (!message) {
			message = {type: 'ping'};
		}
		if (app.globalData.chat_config.SocketTask && app.globalData.chat_config.SocketTask.readyState == 1) {
			app.globalData.chat_config.SocketTask.send({
				data: JSON.stringify(message),
				success: (res) => {
					// console.log(res);
				},
				fail: (res) => {
					// console.error(res);
				}
			});
		} else {
			console.log('消息发送出错', message);
			app.globalData.chat_config.ErrorMsg.push(message);
		}
	},
	/**
	 * 推送来的消息处理
	 * @param {Object} ret
	 */
	handleMsg: function(ret) {
		var app = getApp();
		let that = self;
		if (ret.code == 0) {
			uni.showToast({title: ret.msg || '网络错误',icon: 'none'})
			return;
		}else if(ret.code == 2){
			return;
		}
		switch (ret.type) {
			case 'login':
				//app.globalData.chat_config.emoList = ret.data.chat_memes; // 表情
				app.globalData.chat_config.messageCount = ret.data.unread_num; // 
				uni.$emit("unread_count",{})
				break;
			case 'session_list':
				// 处理会话列表
				this.handleSessionList(ret.data);
				break;
			case 'del_session':
				// 删除会话
				var data = this.del_session_list(ret.data);
				break;
			case 'msg_list':
				// 聊天记录
				var data = this.handleMsgList(ret);
				uni.$emit('msg_list_callback', data);
				break;
			
			case 'join_blacklist':
				// 拉黑用户会话
				var data = this.join_blacklist(ret.data);
				break;
			case 'blacklist':
				// 黑名单列表
				break;
			case 'del_blacklist':
				// 移除黑名单
				// this.wsSend({
				// 	type: 'sessionlist',
				// 	session_time: 0,
				// });
				break;

			case 'new_msg':
				// 好友发消息
				this.newMsgList(ret.data);
				this.setMessageBadge()
				break;
			case 'say':
				//我发送的消息，推给我
				uni.$emit('new_msg_callback', ret.data);
				break;
			case 'set_read':
				break;
			case "message_count":
				app.globalData.chat_config.messageCount = ret.data.unread_num; // 设置底部菜单的角
				uni.$emit("unread_count",{})
			default:
				break;
		}
	},
	/**
	 * 发送消息
	 */
	sendMessage: function(receive_user_id, product_id,content, chat_type = 1) {
		self.wsSend({
			type: 'say',
			receive_user_id: receive_user_id,
			content: content,
			product_id:product_id,
			chat_type: chat_type //类型:1=文字,2=图片,3=商品
		});
	},
	
	//聊天进程列表分页
	handleSessionList: function(data) {
		uni.$emit('session_list_callback', data);
	},
	/**
	 * 聊天消息列表
	 */
	handleMsgList: function(ret) {
		var res = ret.data;
		if (res.total == 0) {
			return {
				data: res,
				receive_user: ret.receiveuser
			};
		}
		var array = [];
		var new_arr = [];
		var min_time = res.data[res.data.length - 1].createtime;
		var min_time_text = res.data[res.data.length - 1].createtime_text;
		array[min_time_text] = [];
		for (let index = res.data.length - 1; index >= 0; index--) {
			const v = res.data[index];
			// 处理表情包
			v.content = v.chat_type == 1 ? self.changeEmotion(v.content) : v.content; // 如果当前时间和最早时间相差不超过10分钟，就分为一组
	
			if (v.createtime - min_time <= 600) {
				array[min_time_text].push(v);
			} else {
				min_time = v.createtime;
				min_time_text = v.createtime_text;
				array[min_time_text] = [];
				array[min_time_text].push(v);
			}
		}
		for (const key in array) {
			new_arr.push({
				time: key,
				data: array[key]
			});
		}
		res.data = new_arr;
		return {
			data: res,
			receive_user: ret.receiveuser
		};
	},
	//处理一个聊天列表分页-暂时未用到
	handle_msg_data: function(data) {
		var new_arr = [];
	
		data.content = data.chat_type == 1 ? self.changeEmotion(data.content) : data.content;
		new_arr.push({
			time: data.createtime_text,
			data: [data]
		});
		return {
			data: new_arr,
		};
	},
	//好友发消息
	newMsgList: function(data) {
		let pages = getCurrentPages();
		if(pages[pages.length - 1].route == 'pages/message/message'){
			//如果在消息页
			uni.$emit("refresh_session",{})
		}else if(pages[pages.length - 1].route == 'pages/chat/chat'){
			//如果在聊天室
			uni.$emit('new_msg_callback', data);
		}
		// uni.vibrateLong({
		// 	success: function() {
		// 		console.log('震动成功');
		// 		self.setMessageBadge(true);
		// 	}
		// });
	},
	
	/**
	 * 聊天消息-处理一个聊天记录按时间分组
	 */
	get_msg_list: function(product_id, receive_user_id, page) {
		self.wsSend({
			type: 'msglist',
			page: page,
			product_id: product_id,
			receive_user_id: receive_user_id
		});	
	},
	
	//删除聊天进程
	del_session_list: function(data) {
		
	},
	// 拉黑用户
	join_blacklist: function(data) {
		
	},
	// 设置底部菜单角标 有底部的页面onshow里都要调用该方法
	setMessageBadge: function(is_need_check = false) {
		var unread_num = getApp().globalData.chat_config.unreadCount; // 判断当前页面是否为tabbar页面，如果是，就设置

		if (is_need_check && getCurrentPages().length > 0) {
			var pages = getCurrentPages(); //获取加载的页面
			var currentPage = pages[pages.length - 1]; //获取当前页面的对象
			var url = currentPage.route; //当前页面url

			var arr = ['pages/index/index', 'pages/message/message',
				'pages/mine/mine','discovery/find/find','pages/want_public/want_public'
			];

			if (arr.indexOf(url) == -1) {
				return false;
			}
		}
		//获取未读消息数
		self.wsSend({
			type: 'getmessagecount'
		});
	},
	//
	changeEmotion: function(contents) {
		var emotions = getApp().globalData.chat_config.emoList;
		var pattern1 = /\[[\u4e00-\u9fa5]+\]/g;
		var pattern2 = /\[[\u4e00-\u9fa5]+\]/;

		if (contents) {
			contents = contents.replace(new RegExp(/\<br>/, 'g'), '\n');
			contents = contents.replace(new RegExp(/\<br\/>/, 'g'), '\n');
		}

		var content = contents.match(pattern1);
		var str = contents;
		var now_str = contents;
		var arr = [];
		if (content == null)
			return [{
				type: 1,
				value: str
			}];

		for (var i = 0; i < content.length; i++) {
			var src = '';

			for (var j = 0; j < emotions.length; j++) {
				if (emotions[j].name == content[i]) {
					src = emotions[j].image;
					break;
				}
			}

			if (!now_str) {
				break;
			}

			var has_i = now_str.indexOf(content[i]);

			if (has_i != -1) {
				arr.push({
					type: 1,
					value: now_str.substring(0, Number(has_i))
				});
				arr.push({
					type: 2,
					value: src
				});
				now_str = now_str.substring(Number(has_i) + Number(content[i].length));

				if (i == content.length - 1) {
					arr.push({
						type: 1,
						value: now_str
					});
				}
			}
		}

		return arr;
	},
	
	formatMsgTime: function(timestamp){
		var mistiming = Math.round((Date.now() - timestamp) / 1000);
		var arrr = ['年', '个月', '星期', '天', '小时', '分钟', '秒'];
		var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];
		
		for (var i = 0; i < arrn.length; i++) {
			var inm = Math.floor(mistiming / arrn[i]);
		
			if (inm != 0) {
				return inm + arrr[i] + '前';
			}
		}
	}
}
module.exports  = self;